﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using CRM.Database.Model;
using CRM.Models;
using System.Linq;
using DevExpress.Web.ASPxUploadControl;
using DevExpress.Web.Mvc;

namespace CRM.Controllers
{
    public class TestController : Controller
    {

        #region Тестирование новых оборотов

        [HttpGet]
        [CheckAccessAttribute]
        public ActionResult Turnovers()
        {
            var turnoverType = new CRM.Database.Model.TurnoverType {IdProductMark = 1, IdTurnoverClassification = 1};
            return View(turnoverType);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult Turnovers(HttpPostedFileBase file, [ModelBinder(typeof(DevExpressEditorsBinder))] TurnoverType turnoverType)
        {
            var confCol = new CRM.Database.Model.ConfigurationsCollection();
            var turnoversCol = new CRM.Database.Model.TurnoversCollection();
            //проверка - прикреплен ли файл?
            if(file == null)
            {
                ViewData["error"] = "Не найден прикрепляемый файл";
                return View("Error");
            }

            //проверка типа загруженного файла
            if(!Utilites.FileUtilites.ValidateExtention(file, "xls") && !Utilites.FileUtilites.ValidateExtention(file, "xlsx"))
            {
                ViewData["error"] = "Загружен неправельный тип файла";
                return View("Error");
            }

            //сохранениe XLS файла
            var filepath = Utilites.FileUtilites.SaveUplodedFile(file, 
                                        Guid.NewGuid() + "." + Utilites.FileUtilites.GetFileExtention(file), 
                                        confCol.TurnoversFilesUploadPath);
            if(string.IsNullOrEmpty(filepath))
            {
                ViewData["error"] = "Ошибка сохранения файла";
                return View("Error");
            }
            
            //чтение данных из файла в таблицу 
            var dataTable = Utilites.FileUtilites.GetDataTableFromXlsFile(filepath);
            if(dataTable == null)
            {
                ViewData["error"] = "Ошибка чтения данных из первого листа Excel файла. Возможно первый лист пустой.";
                return View("Error");
            }

            //анализ и запись оборотов
            var result = turnoversCol.InsertTurnovers(dataTable, turnoverType.IdTurnoverClassification,
                                                      turnoverType.IdProductMark);
            ViewData["Log"] = result;

            return View();
        }

        #endregion

        public ActionResult Index()
        {
            return View();//DB.GetCustomerById(-13).SequentialNumber);
        }
        
        public ActionResult SettlementsChooserGrid()
        {
            return PartialView();
        }

        public ActionResult Test1()
        {
            return View();
        }

        //[HttpPost]
        //public ActionResult SettlementsChooserGrid([ModelBinder(typeof(DevExpressEditorsBinder))] Settlements model)
        //{
        //    return PartialView();
        //}

        [HttpPost]
        public ActionResult SettlementsChooser([ModelBinder(typeof(DevExpressEditorsBinder))] Settlements set)
    {
        return View(set);
    }

        public ActionResult TurnoversFullList()
        {
            return View("TurnoversFullList", CRM.Database.Model.DB.Entities.v_TrueTurnovers.ToList());
        }

        public ActionResult TurnoversFullListPartion()
        {
            return View(CRM.Database.Model.DB.Entities.v_TrueTurnovers.ToList());
        }

        [HttpGet]
        public ActionResult FileUploadPartial()
        {
            Session["Storage"] = new UploadControlFilesStorage();
            return View("FileUploadPartial");
        }
        [HttpPost]
        public ActionResult FileUploadPartial(FormCollection form)
        {
            if (Request.Params["add"] != null)
            {
                UploadedFile[] files = UploadControlExtension.GetUploadedFiles("ucMultiFile", UploadControlDemosHelper.ValidationSettings);
                UploadControlDemosHelper.AddImagesToCollection(files);
            }
            else if (Request.Params["clear"] != null)
            {
                UploadControlDemosHelper.ClearImageCollection();
            }
            return View("Index");
        }

        public ActionResult EquipmentTypesPartial()
        {
            return PartialView("ComboTest");
        }

        //public FileResult TestFile()
        //{
        //    var confCol = new ConfigurationsCollection();
           
        //    return File(confCol.ContractsPath +  @"\contract1.doc", "application/vnd.openxmlformats-officedocument.wordprocessingml.document").;
        //}
    }

    public class UploadControlDemosHelper
    {
        public const string UploadDirectory = "~/Content/UploadControl/UploadFolder/";
        public const string ThumbnailFormat = "Thumbnail{0}{1}";

        public static readonly ValidationSettings ValidationSettings = new ValidationSettings
        {
            AllowedFileExtensions = new string[] { ".jpg", ".jpeg", ".jpe", ".gif" },
            MaxFileSize = 20971520
        };

        public static List<string> Files
        {
            get
            {
                UploadControlFilesStorage storage = HttpContext.Current.Session["Storage"] as UploadControlFilesStorage;
                if (storage != null)
                    return storage.Files;
                return new List<string>();
            }
        }
        public static int FileInputCount
        {
            get
            {
                UploadControlFilesStorage storage = HttpContext.Current.Session["Storage"] as UploadControlFilesStorage;
                if (storage != null)
                    return storage.FileInputCount;
                return 2;
            }
        }

        public static void AddImagesToCollection(UploadedFile[] files)
        {
            UploadControlFilesStorage storage = HttpContext.Current.Session["Storage"] as UploadControlFilesStorage;
            if (storage != null)
            {
                for (int i = 0; i < files.Length; i++)
                {
                    if (files[i].FileBytes.Length > 0 && files[i].IsValid)
                    {
                        if (!storage.Files.Contains(files[i].FileName))
                        {
                            string filePath = UploadDirectory + string.Format(ThumbnailFormat, storage.Files.Count, Path.GetExtension(files[i].FileName));
                            files[i].SaveAs(HttpContext.Current.Request.MapPath(filePath));
                            storage.Files.Add(files[i].FileName);
                        }
                    }
                }
                storage.FileInputCount = files.Length;
            }
        }
        public static void ClearImageCollection()
        {
            UploadControlFilesStorage storage = HttpContext.Current.Session["Storage"] as UploadControlFilesStorage;
            if (storage != null)
                storage.Files.Clear();
        }

        public static void ucCallbacks_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            if (e.UploadedFile.IsValid)
            {
                string resultFilePath = UploadDirectory + string.Format(ThumbnailFormat, "", Path.GetExtension(e.UploadedFile.FileName));
               // using (Image original = Image.FromStream(e.UploadedFile.FileContent))
                //using (Image thumbnail = PhotoUtils.Inscribe(original, 100))
                //{
                //    PhotoUtils.SaveToJpeg(thumbnail, HttpContext.Current.Request.MapPath(resultFilePath));
                //}
                //IUrlResolutionService urlResolver = sender as IUrlResolutionService;
                //if (urlResolver != null)
                //    e.CallbackData = urlResolver.ResolveClientUrl(resultFilePath) + "?refresh=" + Guid.NewGuid().ToString();
            }
        }
        public static void ucMultiSelection_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            string resultFilePath = UploadDirectory + e.UploadedFile.FileName;
            e.UploadedFile.SaveAs(HttpContext.Current.Request.MapPath(resultFilePath));

          //  UploadingUtils.RemoveFileWithDelay(e.UploadedFile.FileName, HttpContext.Current.Request.MapPath(resultFilePath), 5);

            IUrlResolutionService urlResolver = sender as IUrlResolutionService;
            if (urlResolver != null)
            {
                string file = string.Format("{0} ({1}) {2}KB", e.UploadedFile.FileName, e.UploadedFile.ContentType, e.UploadedFile.ContentLength / 1024);
                string url = urlResolver.ResolveClientUrl(resultFilePath);
                e.CallbackData = file + "|" + url;
            }
        }
    }

    public class UploadControlFilesStorage
    {
        List<string> files;

        public UploadControlFilesStorage()
        {
            this.files = new List<string>();
            FileInputCount = 2;
        }

        public int FileInputCount { get; set; }
        public List<string> Files { get { return files; } }
    }



}
